<template>
  <div class="asset-groups-container">
    <el-card class="asset-groups-card">
      <template #header>
        <div class="card-header">
          <h2>资产分组管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateGroupDialog = true">
              <el-icon><Plus /></el-icon>
              新建分组
            </el-button>
            <el-button @click="importAssets">
              <el-icon><Upload /></el-icon>
              导入资产
            </el-button>
            <el-button @click="exportSelectedGroups">
              <el-icon><Download /></el-icon>
              导出选中
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-filter-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchQuery"
              placeholder="搜索分组名称或描述"
              prefix-icon="Search"
              clearable
              @input="handleSearch"
            />
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="filterGroupType"
              placeholder="选择分组类型"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="type in groupTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="filterRiskLevel"
              placeholder="选择风险等级"
              clearable
              @change="handleFilter"
            >
              <el-option label="低风险" value="low" />
              <el-option label="中风险" value="medium" />
              <el-option label="高风险" value="high" />
              <el-option label="严重" value="critical" />
            </el-select>
          </el-col>
        </el-row>
      </div>

      <!-- 分组列表 -->
      <div class="groups-table-container">
        <el-table
          v-loading="loading"
          :data="paginatedGroups"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @row-dblclick="editGroup"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="分组名称" min-width="180">
            <template #default="scope">
              <div class="group-name-cell">
                <div class="group-name">{{ scope.row.name }}</div>
                <div class="group-type">
                  <el-tag size="small" :type="getGroupTypeTag(scope.row.type)">
                    {{ getGroupTypeLabel(scope.row.type) }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="assetCount" label="资产数量" width="100" align="center">
            <template #default="scope">
              <el-badge :value="scope.row.assetCount" type="info" />
            </template>
          </el-table-column>
          <el-table-column label="风险等级" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getRiskLevelTag(scope.row.riskLevel)" effect="dark">
                {{ getRiskLevelLabel(scope.row.riskLevel) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200">
            <template #default="scope">
              <div class="group-description" :title="scope.row.description">
                {{ scope.row.description }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="最近扫描" width="150">
            <template #default="scope">
              {{ scope.row.lastScanTime ? formatDate(scope.row.lastScanTime) : '从未扫描' }}
            </template>
          </el-table-column>
          <el-table-column prop="tags" label="标签" min-width="120">
            <template #default="scope">
              <div class="group-tags">
                <el-tag 
                  v-for="tag in scope.row.tags" 
                  :key="tag"
                  size="small"
                  effect="plain"
                  class="mr-2"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="editGroup(scope.row)"
                size="small"
                title="编辑分组"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="primary"
                @click="viewAssets(scope.row)"
                size="small"
                title="查看资产"
              >
                <el-icon><View /></el-icon>
              </el-button>
              <el-button
                type="primary"
                @click="scanGroup(scope.row)"
                size="small"
                title="扫描分组"
              >
                <el-icon><Play /></el-icon>
              </el-button>
              <el-button
                type="danger"
                link
                @click="deleteGroup(scope.row)"
                size="small"
                title="删除分组"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredGroups.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑分组对话框 -->
    <el-dialog
      v-model="showCreateGroupDialog"
      :title="editingGroup ? '编辑资产分组' : '新建资产分组'"
      width="700px"
      @close="resetGroupForm"
    >
      <el-form
        ref="groupFormRef"
        :model="groupForm"
        :rules="groupFormRules"
        label-width="120px"
      >
        <el-form-item label="分组名称" prop="name">
          <el-input
            v-model="groupForm.name"
            placeholder="请输入分组名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="分组类型" prop="type">
          <el-select
            v-model="groupForm.type"
            placeholder="请选择分组类型"
          >
            <el-option
              v-for="type in groupTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="groupForm.description"
            type="textarea"
            placeholder="请输入分组描述"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input
            v-model="groupForm.contactPerson"
            placeholder="请输入联系人"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="contactEmail">
          <el-input
            v-model="groupForm.contactEmail"
            placeholder="请输入联系邮箱"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="groupForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
            style="width: 100%"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务重要性" prop="businessImportance">
          <el-rate 
            v-model="groupForm.businessImportance" 
            :max="5"
            show-score
          />
        </el-form-item>
        <el-form-item label="合规要求" prop="complianceRequirements">
          <el-checkbox-group v-model="groupForm.complianceRequirements">
            <el-checkbox 
              v-for="req in complianceRequirements" 
              :key="req.value"
              :label="req.value"
              border
              class="mr-4 mb-2"
            >
              {{ req.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="groupForm.notes"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="2"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateGroupDialog = false">取消</el-button>
          <el-button type="primary" @click="saveGroup">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 资产管理对话框 -->
    <el-dialog
      v-model="showAssetsDialog"
      :title="`资产管理 - ${selectedGroup?.name}`"
      width="800px"
    >
      <div class="assets-dialog-container">
        <div class="assets-header">
          <div class="assets-info">
            <el-badge :value="viewAssetsList.length" type="info">资产总数</el-badge>
            <el-badge :value="onlineAssetsCount" type="success" class="ml-4">在线资产</el-badge>
            <el-badge :value="vulnerableAssetsCount" type="danger" class="ml-4">有漏洞资产</el-badge>
          </div>
          <div class="assets-actions">
            <el-button @click="showAddAssetDialog = true">
              <el-icon><Plus /></el-icon>
              添加资产
            </el-button>
            <el-upload
              class="upload-demo"
              action=""
              :http-request="handleUpload"
              :show-file-list="false"
              accept=".txt,.csv"
              :before-upload="beforeUpload"
            >
              <el-button>
                <el-icon><Upload /></el-icon>
                批量导入
              </el-button>
            </el-upload>
            <el-button @click="exportAssets">
              <el-icon><Download /></el-icon>
              导出资产
            </el-button>
          </div>
        </div>

        <div class="assets-search">
          <el-input
            v-model="assetSearchQuery"
            placeholder="搜索资产IP或名称"
            prefix-icon="Search"
            clearable
            @input="handleAssetSearch"
          />
        </div>

        <el-table
          v-loading="assetsLoading"
          :data="paginatedViewAssets"
          style="width: 100%"
          @selection-change="handleAssetSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="ip" label="IP地址" min-width="120" />
          <el-table-column prop="hostname" label="主机名" min-width="150" />
          <el-table-column prop="os" label="操作系统" min-width="120" />
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'online' ? 'success' : 'danger'">
                {{ scope.row.status === 'online' ? '在线' : '离线' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastScanTime" label="最近扫描" width="150">
            <template #default="scope">
              {{ scope.row.lastScanTime ? formatDate(scope.row.lastScanTime) : '未扫描' }}
            </template>
          </el-table-column>
          <el-table-column label="开放端口" width="100" align="center">
            <template #default="scope">
              <el-badge v-if="scope.row.openPorts > 0" :value="scope.row.openPorts" type="warning" />
              <span v-else>0</span>
            </template>
          </el-table-column>
          <el-table-column label="漏洞数" width="100" align="center">
            <template #default="scope">
              <el-badge v-if="scope.row.vulnerabilityCount > 0" :value="scope.row.vulnerabilityCount" type="danger" />
              <span v-else>0</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="editAsset(scope.row)"
                size="small"
                title="编辑资产"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="danger"
                link
                @click="deleteAsset(scope.row)"
                size="small"
                title="删除资产"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="assets-pagination">
          <el-pagination
            v-model:current-page="currentAssetPage"
            v-model:page-size="assetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredViewAssets.length"
            @size-change="handleAssetSizeChange"
            @current-change="handleAssetCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAssetsDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加/编辑资产对话框 -->
    <el-dialog
      v-model="showAddAssetDialog"
      :title="editingAsset ? '编辑资产' : '添加资产'"
      width="600px"
    >
      <el-form
        ref="assetFormRef"
        :model="assetForm"
        :rules="assetFormRules"
        label-width="120px"
      >
        <el-form-item label="IP地址" prop="ip">
          <el-input
            v-model="assetForm.ip"
            placeholder="请输入资产IP地址"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="主机名" prop="hostname">
          <el-input
            v-model="assetForm.hostname"
            placeholder="请输入主机名"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="操作系统" prop="os">
          <el-input
            v-model="assetForm.os"
            placeholder="请输入操作系统"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="操作系统版本" prop="osVersion">
          <el-input
            v-model="assetForm.osVersion"
            placeholder="请输入操作系统版本"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="MAC地址" prop="macAddress">
          <el-input
            v-model="assetForm.macAddress"
            placeholder="请输入MAC地址"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="资产类型" prop="type">
          <el-select
            v-model="assetForm.type"
            placeholder="请选择资产类型"
          >
            <el-option label="服务器" value="server" />
            <el-option label="工作站" value="workstation" />
            <el-option label="网络设备" value="network" />
            <el-option label="IoT设备" value="iot" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-select
            v-model="assetForm.businessType"
            placeholder="请选择业务类型"
          >
            <el-option label="Web服务" value="web" />
            <el-option label="数据库" value="database" />
            <el-option label="文件服务" value="file" />
            <el-option label="邮件服务" value="mail" />
            <el-option label="应用服务" value="application" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="assetForm.notes"
            type="textarea"
            placeholder="请输入备注信息"
            :rows="2"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddAssetDialog = false">取消</el-button>
          <el-button type="primary" @click="saveAsset">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 扫描分组对话框 -->
    <el-dialog
      v-model="showScanGroupDialog"
      :title="`扫描分组 - ${selectedGroup?.name}`"
      width="600px"
    >
      <el-form
        ref="scanGroupFormRef"
        :model="scanGroupForm"
        :rules="scanGroupFormRules"
        label-width="120px"
      >
        <el-form-item label="扫描策略" prop="policyId">
          <el-select
            v-model="scanGroupForm.policyId"
            placeholder="请选择扫描策略"
          >
            <el-option
              v-for="policy in availablePolicies"
              :key="policy.id"
              :label="policy.name"
              :value="policy.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="扫描名称" prop="scanName">
          <el-input
            v-model="scanGroupForm.scanName"
            placeholder="请输入扫描任务名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="基准分组">
          <el-tag>{{ selectedGroup?.name }}</el-tag>
        </el-form-item>
        <el-form-item label="通知配置">
          <el-checkbox-group v-model="scanGroupForm.notifications">
            <el-checkbox label="email" border class="mr-4">邮件</el-checkbox>
            <el-checkbox label="webhook" border class="mr-4">Webhook</el-checkbox>
            <el-checkbox label="system" border>系统通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="扫描优先级">
          <el-radio-group v-model="scanGroupForm.priority">
            <el-radio-button label="low">低</el-radio-button>
            <el-radio-button label="medium">中</el-radio-button>
            <el-radio-button label="high">高</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showScanGroupDialog = false">取消</el-button>
          <el-button type="primary" @click="executeGroupScan" :loading="isExecutingGroupScan">开始扫描</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Play, Upload, Download, Search, View } from '@element-plus/icons-vue'
import apiService from '../services/apiService.js'
import { formatDate } from '../utils/dateUtils.js'

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const filterGroupType = ref('')
const filterRiskLevel = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const selectedGroups = ref([])
const showCreateGroupDialog = ref(false)
const showAssetsDialog = ref(false)
const showAddAssetDialog = ref(false)
const showScanGroupDialog = ref(false)
const editingGroup = ref(null)
const editingAsset = ref(null)
const selectedGroup = ref(null)
const assetsLoading = ref(false)
const assetSearchQuery = ref('')
const currentAssetPage = ref(1)
const assetPageSize = ref(10)
const selectedAssets = ref([])
const isExecutingGroupScan = ref(false)
const allGroups = ref([])
const viewAssetsList = ref([])
const availablePolicies = ref([])

// 分组表单
const groupForm = reactive({
  name: '',
  type: 'business_unit',
  description: '',
  contactPerson: '',
  contactEmail: '',
  tags: [],
  businessImportance: 3,
  complianceRequirements: [],
  notes: ''
})

// 资产表单
const assetForm = reactive({
  ip: '',
  hostname: '',
  os: '',
  osVersion: '',
  macAddress: '',
  type: 'server',
  businessType: 'web',
  notes: ''
})

// 扫描分组表单
const scanGroupForm = reactive({
  policyId: '',
  scanName: '',
  notifications: ['system'],
  priority: 'medium'
})

// 表单验证规则
const groupFormRules = {
  name: [
    { required: true, message: '请输入分组名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择分组类型', trigger: 'change' }
  ],
  contactEmail: [
    {
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      message: '请输入有效的邮箱地址',
      trigger: 'blur',
      required: false
    }
  ]
}

const assetFormRules = {
  ip: [
    { required: true, message: '请输入资产IP地址', trigger: 'blur' },
    {
      pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^\[(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\]$/,
      message: '请输入有效的IP地址',
      trigger: 'blur'
    }
  ]
}

const scanGroupFormRules = {
  policyId: [
    { required: true, message: '请选择扫描策略', trigger: 'change' }
  ],
  scanName: [
    { required: true, message: '请输入扫描任务名称', trigger: 'blur' }
  ]
}

// 分组类型选项
const groupTypes = [
  { label: '业务部门', value: 'business_unit' },
  { label: '服务器集群', value: 'server_cluster' },
  { label: '网络区域', value: 'network_segment' },
  { label: '应用系统', value: 'application' },
  { label: '开发环境', value: 'dev_environment' },
  { label: '测试环境', value: 'test_environment' },
  { label: '生产环境', value: 'prod_environment' },
  { label: '自定义', value: 'custom' }
]

// 合规要求选项
const complianceRequirements = [
  { label: '等保2.0', value: 'grade_protection_2' },
  { label: 'PCI DSS', value: 'pci_dss' },
  { label: 'GDPR', value: 'gdpr' },
  { label: 'ISO27001', value: 'iso27001' },
  { label: 'HIPAA', value: 'hipaa' },
  { label: 'SOX', value: 'sox' }
]

// 常见标签
const commonTags = [
  '核心业务', '重要资产', '外部访问', '内部系统', 
  '数据库服务器', 'Web服务器', '邮件服务器', '文件服务器',
  '备份服务器', '负载均衡', '防火墙', 'VPN设备',
  '监控系统', '存储设备', '测试系统', '开发系统'
]

// 计算属性
const filteredGroups = computed(() => {
  let result = [...allGroups.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(group => 
      group.name.toLowerCase().includes(query) ||
      group.description.toLowerCase().includes(query)
    )
  }
  
  // 类型过滤
  if (filterGroupType.value) {
    result = result.filter(group => group.type === filterGroupType.value)
  }
  
  // 风险等级过滤
  if (filterRiskLevel.value) {
    result = result.filter(group => group.riskLevel === filterRiskLevel.value)
  }
  
  return result
})

const paginatedGroups = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredGroups.value.slice(start, end)
})

const filteredViewAssets = computed(() => {
  let result = [...viewAssetsList.value]
  
  // 搜索过滤
  if (assetSearchQuery.value) {
    const query = assetSearchQuery.value.toLowerCase()
    result = result.filter(asset => 
      asset.ip.toLowerCase().includes(query) ||
      (asset.hostname && asset.hostname.toLowerCase().includes(query))
    )
  }
  
  return result
})

const paginatedViewAssets = computed(() => {
  const start = (currentAssetPage.value - 1) * assetPageSize.value
  const end = start + assetPageSize.value
  return filteredViewAssets.value.slice(start, end)
})

const onlineAssetsCount = computed(() => {
  return viewAssetsList.value.filter(asset => asset.status === 'online').length
})

const vulnerableAssetsCount = computed(() => {
  return viewAssetsList.value.filter(asset => asset.vulnerabilityCount > 0).length
})

// 方法
const loadGroups = async () => {
  loading.value = true
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.getAssetGroups()
    // allGroups.value = response
    
    // 模拟数据
    allGroups.value = [
      {
        id: '1',
        name: '核心业务系统',
        type: 'business_unit',
        assetCount: 45,
        riskLevel: 'high',
        description: '公司核心业务系统相关资产',
        contactPerson: '张三',
        contactEmail: 'zhangsan@example.com',
        tags: ['核心业务', '重要资产', '外部访问'],
        businessImportance: 5,
        complianceRequirements: ['grade_protection_2', 'pci_dss'],
        lastScanTime: '2024-01-15T10:30:00Z',
        notes: '需定期进行安全扫描和渗透测试'
      },
      {
        id: '2',
        name: '开发测试环境',
        type: 'dev_environment',
        assetCount: 38,
        riskLevel: 'low',
        description: '开发和测试使用的环境资产',
        contactPerson: '李四',
        contactEmail: 'lisi@example.com',
        tags: ['开发系统', '测试系统'],
        businessImportance: 2,
        complianceRequirements: [],
        lastScanTime: '2024-01-18T14:20:00Z',
        notes: '定期清理测试数据'
      },
      {
        id: '3',
        name: '数据中心服务器',
        type: 'server_cluster',
        assetCount: 62,
        riskLevel: 'critical',
        description: '数据中心的核心服务器集群',
        contactPerson: '王五',
        contactEmail: 'wangwu@example.com',
        tags: ['数据库服务器', '存储设备', '重要资产'],
        businessImportance: 5,
        complianceRequirements: ['grade_protection_2', 'iso27001'],
        lastScanTime: '2024-01-20T09:45:00Z',
        notes: '关键基础设施，需特别关注安全状况'
      },
      {
        id: '4',
        name: '外部网站集群',
        type: 'web_servers',
        assetCount: 15,
        riskLevel: 'high',
        description: '面向外部用户的网站服务器集群',
        contactPerson: '赵六',
        contactEmail: 'zhaoliu@example.com',
        tags: ['Web服务器', '外部访问'],
        businessImportance: 4,
        complianceRequirements: ['grade_protection_2'],
        lastScanTime: '2024-01-19T16:30:00Z',
        notes: '直接暴露在互联网上，安全风险较高'
      },
      {
        id: '5',
        name: '内部办公网络',
        type: 'network_segment',
        assetCount: 120,
        riskLevel: 'medium',
        description: '公司内部办公网络设备和终端',
        contactPerson: '孙七',
        contactEmail: 'sunqi@example.com',
        tags: ['内部系统', '终端设备'],
        businessImportance: 3,
        complianceRequirements: [],
        lastScanTime: '2024-01-17T11:20:00Z',
        notes: '包含员工电脑和内部服务器'
      }
    ]
  } catch (error) {
    console.error('加载资产分组失败:', error)
    ElMessage.error('加载资产分组失败，请重试')
  } finally {
    loading.value = false
  }
}

const loadAvailablePolicies = async () => {
  try {
    // 模拟获取可用扫描策略
    availablePolicies.value = [
      { id: '1', name: '全面安全扫描' },
      { id: '2', name: '快速漏洞检测' },
      { id: '3', name: '深度渗透测试' },
      { id: '4', name: '合规性检查' },
      { id: '5', name: 'Web应用专项' }
    ]
  } catch (error) {
    console.error('加载扫描策略失败:', error)
  }
}

const loadGroupAssets = async (groupId) => {
  assetsLoading.value = true
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.getGroupAssets(groupId)
    // viewAssetsList.value = response
    
    // 模拟数据
    const assetCount = allGroups.value.find(g => g.id === groupId)?.assetCount || 10
    viewAssetsList.value = Array.from({ length: Math.min(20, assetCount) }, (_, index) => ({
      id: `${groupId}-${index + 1}`,
      ip: `192.168.1.${100 + index}`,
      hostname: `server-${groupId}-${index + 1}`,
      os: index % 3 === 0 ? 'Windows Server' : index % 3 === 1 ? 'Linux CentOS' : 'Linux Ubuntu',
      osVersion: index % 3 === 0 ? '2019' : index % 3 === 1 ? '7.9' : '20.04',
      macAddress: `00:1B:44:11:${Math.floor(Math.random() * 100).toString().padStart(2, '0')}:${Math.floor(Math.random() * 100).toString().padStart(2, '0')}`,
      type: index % 4 === 0 ? 'server' : index % 4 === 1 ? 'network' : index % 4 === 2 ? 'workstation' : 'other',
      businessType: index % 5 === 0 ? 'web' : index % 5 === 1 ? 'database' : index % 5 === 2 ? 'file' : index % 5 === 3 ? 'application' : 'other',
      status: Math.random() > 0.2 ? 'online' : 'offline',
      openPorts: Math.floor(Math.random() * 20),
      vulnerabilityCount: Math.floor(Math.random() * 15),
      lastScanTime: Math.random() > 0.3 ? '2024-01-20T10:30:00Z' : null,
      notes: '模拟资产数据'
    }))
  } catch (error) {
    console.error('加载分组资产失败:', error)
    ElMessage.error('加载分组资产失败，请重试')
  } finally {
    assetsLoading.value = false
  }
}

const saveGroup = async () => {
  // 验证表单
  const groupFormRef = ref(null)
  if (!groupFormRef.value) {
    ElMessage.warning('表单验证失败')
    return
  }
  
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    if (editingGroup.value) {
      // 更新现有分组
      const index = allGroups.value.findIndex(g => g.id === editingGroup.value.id)
      if (index !== -1) {
        allGroups.value[index] = { 
          ...groupForm, 
          id: editingGroup.value.id,
          assetCount: editingGroup.value.assetCount || 0,
          riskLevel: editingGroup.value.riskLevel || 'low',
          lastScanTime: editingGroup.value.lastScanTime
        }
      }
      ElMessage.success('资产分组更新成功')
    } else {
      // 创建新分组
      const newGroup = {
        ...groupForm,
        id: String(allGroups.value.length + 1),
        assetCount: 0,
        riskLevel: 'low',
        lastScanTime: null
      }
      allGroups.value.unshift(newGroup)
      ElMessage.success('资产分组创建成功')
    }
    
    showCreateGroupDialog.value = false
    resetGroupForm()
  } catch (error) {
    console.error('保存资产分组失败:', error)
    ElMessage.error('保存资产分组失败，请重试')
  }
}

const deleteGroup = async (group) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除资产分组"${group.name}"吗？此操作将删除该分组下的所有资产关系。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里模拟API调用，实际项目中应该调用真实API
    allGroups.value = allGroups.value.filter(g => g.id !== group.id)
    ElMessage.success('资产分组删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const importAssets = () => {
  // 这里应该实现导入功能，打开文件选择器
  ElMessage.info('导入资产功能待实现')
}

const exportSelectedGroups = () => {
  if (selectedGroups.value.length === 0) {
    ElMessage.warning('请选择要导出的资产分组')
    return
  }
  
  // 这里应该实现导出功能
  ElMessage.success(`已导出${selectedGroups.value.length}个资产分组`)
}

const editGroup = (group) => {
  editingGroup.value = group
  // 深拷贝以避免直接修改原对象
  const groupCopy = JSON.parse(JSON.stringify(group))
  Object.assign(groupForm, groupCopy)
  showCreateGroupDialog.value = true
}

const viewAssets = (group) => {
  selectedGroup.value = group
  loadGroupAssets(group.id)
  showAssetsDialog.value = true
}

const scanGroup = (group) => {
  selectedGroup.value = group
  scanGroupForm.scanName = `${group.name} - ${formatDate(new Date())}`
  scanGroupForm.policyId = ''
  scanGroupForm.notifications = ['system']
  scanGroupForm.priority = 'medium'
  showScanGroupDialog.value = true
}

const executeGroupScan = async () => {
  // 验证表单
  const scanGroupFormRef = ref(null)
  if (!scanGroupFormRef.value) {
    ElMessage.warning('表单验证失败')
    return
  }
  
  isExecutingGroupScan.value = true
  
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.createGroupScanTask({
    //   ...scanGroupForm,
    //   groupId: selectedGroup.value.id
    // })
    
    // 模拟成功响应
    setTimeout(() => {
      ElMessage.success(`扫描任务 "${scanGroupForm.scanName}" 已创建成功`)
      showScanGroupDialog.value = false
      isExecutingGroupScan.value = false
    }, 1500)
  } catch (error) {
    console.error('创建分组扫描任务失败:', error)
    ElMessage.error('创建分组扫描任务失败，请重试')
    isExecutingGroupScan.value = false
  }
}

const saveAsset = async () => {
  // 验证表单
  const assetFormRef = ref(null)
  if (!assetFormRef.value) {
    ElMessage.warning('表单验证失败')
    return
  }
  
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    if (editingAsset.value) {
      // 更新现有资产
      const index = viewAssetsList.value.findIndex(a => a.id === editingAsset.value.id)
      if (index !== -1) {
        viewAssetsList.value[index] = { ...assetForm, id: editingAsset.value.id }
      }
      ElMessage.success('资产更新成功')
    } else {
      // 创建新资产
      const newAsset = {
        ...assetForm,
        id: `${selectedGroup.value.id}-${viewAssetsList.value.length + 1}`,
        status: 'unknown',
        openPorts: 0,
        vulnerabilityCount: 0,
        lastScanTime: null
      }
      viewAssetsList.value.push(newAsset)
      
      // 更新分组资产数量
      const groupIndex = allGroups.value.findIndex(g => g.id === selectedGroup.value.id)
      if (groupIndex !== -1) {
        allGroups.value[groupIndex].assetCount++
      }
      
      ElMessage.success('资产添加成功')
    }
    
    showAddAssetDialog.value = false
    resetAssetForm()
  } catch (error) {
    console.error('保存资产失败:', error)
    ElMessage.error('保存资产失败，请重试')
  }
}

const deleteAsset = async (asset) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除资产"${asset.ip}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里模拟API调用，实际项目中应该调用真实API
    viewAssetsList.value = viewAssetsList.value.filter(a => a.id !== asset.id)
    
    // 更新分组资产数量
    const groupIndex = allGroups.value.findIndex(g => g.id === selectedGroup.value.id)
    if (groupIndex !== -1) {
      allGroups.value[groupIndex].assetCount--
    }
    
    ElMessage.success('资产删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const editAsset = (asset) => {
  editingAsset.value = asset
  // 深拷贝以避免直接修改原对象
  const assetCopy = JSON.parse(JSON.stringify(asset))
  Object.assign(assetForm, assetCopy)
  showAddAssetDialog.value = true
}

const handleUpload = (file) => {
  // 这里应该实现文件上传和解析逻辑
  ElMessage.success(`文件"${file.file.name}"上传成功，共导入X条资产`)
}

const beforeUpload = (file) => {
  const isTxtOrCsv = file.type === 'text/plain' || file.type === 'text/csv' || file.name.endsWith('.txt') || file.name.endsWith('.csv')
  if (!isTxtOrCsv) {
    ElMessage.error('请上传.txt或.csv格式的文件！')
  }
  return isTxtOrCsv
}

const exportAssets = () => {
  // 这里应该实现导出功能
  ElMessage.success(`已导出${viewAssetsList.value.length}条资产数据`)
}

const handleSelectionChange = (selection) => {
  selectedGroups.value = selection
}

const handleAssetSelectionChange = (selection) => {
  selectedAssets.value = selection
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleAssetSearch = () => {
  currentAssetPage.value = 1
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
}

const handleCurrentChange = (newCurrent) => {
  currentPage.value = newCurrent
}

const handleAssetSizeChange = (newSize) => {
  assetPageSize.value = newSize
}

const handleAssetCurrentChange = (newCurrent) => {
  currentAssetPage.value = newCurrent
}

const resetGroupForm = () => {
  Object.assign(groupForm, {
    name: '',
    type: 'business_unit',
    description: '',
    contactPerson: '',
    contactEmail: '',
    tags: [],
    businessImportance: 3,
    complianceRequirements: [],
    notes: ''
  })
  editingGroup.value = null
}

const resetAssetForm = () => {
  Object.assign(assetForm, {
    ip: '',
    hostname: '',
    os: '',
    osVersion: '',
    macAddress: '',
    type: 'server',
    businessType: 'web',
    notes: ''
  })
  editingAsset.value = null
}

// 辅助函数
const getGroupTypeTag = (type) => {
  const typeMap = {
    'business_unit': 'primary',
    'server_cluster': 'success',
    'network_segment': 'warning',
    'application': 'danger',
    'dev_environment': 'info',
    'test_environment': 'info',
    'prod_environment': 'warning',
    'custom': 'default'
  }
  return typeMap[type] || 'default'
}

const getGroupTypeLabel = (type) => {
  const labelMap = groupTypes.reduce((map, t) => {
    map[t.value] = t.label
    return map
  }, {})
  return labelMap[type] || type
}

const getRiskLevelTag = (level) => {
  const levelMap = {
    'low': 'success',
    'medium': 'warning',
    'high': 'danger',
    'critical': 'danger'
  }
  return levelMap[level] || 'default'
}

const getRiskLevelLabel = (level) => {
  const labelMap = {
    'low': '低风险',
    'medium': '中风险',
    'high': '高风险',
    'critical': '严重'
  }
  return labelMap[level] || level
}

// 组件挂载时加载数据
onMounted(() => {
  loadGroups()
  loadAvailablePolicies()
})
</script>

<style scoped>
.asset-groups-container {
  padding: 20px;
}

.asset-groups-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-filter-container {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.groups-table-container {
  overflow-x: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.group-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.group-name {
  font-weight: 500;
}

.group-description {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.group-tags {
  display: flex;
  flex-wrap: wrap;
}

.mr-2 {
  margin-right: 8px;
}

.mr-4 {
  margin-right: 16px;
}

.mb-2 {
  margin-bottom: 8px;
}

/* 资产对话框样式 */
.assets-dialog-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.assets-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.assets-info {
  display: flex;
  align-items: center;
}

.assets-actions {
  display: flex;
  gap: 10px;
}

.assets-search {
  margin-bottom: 10px;
}

.assets-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .asset-groups-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .search-filter-container {
    padding: 12px;
  }
  
  .el-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .el-col {
    width: 100% !important;
  }
  
  .assets-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .assets-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style>